package com.cens.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cens.common.constant.AuthConstant;
import com.cens.common.utils.HttpUtils;
import com.cens.common.utils.R;
import com.cens.mall.auth.dto.SocialWeiboUser;
import com.cens.mall.auth.feign.MemberFeignService;
import com.cens.common.vo.MemberEntityVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
//        https://api.weibo.com/oauth2/access_token?
//        client_id=YOUR_CLIENT_ID&
//        client_secret=YOUR_CLIENT_SECRET&
//        grant_type=authorization_code&
//        redirect_uri=YOUR_REGISTERED_REDIRECT_URI&
//        code=CODE
        HashMap<String, String> headers = new HashMap<>();
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","3233757939");
        map.put("client_secret","d6340418e36c376ad69d9a89fc6fe7f3");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.censmall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, null,map);

        //处理返回结果
        if(response.getStatusLine().getStatusCode() == 200){
            String result = EntityUtils.toString(response.getEntity());
            SocialWeiboUser socialWeiboUser = JSON.parseObject(result, SocialWeiboUser.class);
            //登录或注册
            R res = memberFeignService.socialLogin(socialWeiboUser);
            if(res.getCode() == 0){
                MemberEntityVo data = res.getData("data", new TypeReference<MemberEntityVo>() {
                });
                log.info("登录成功 用户信息" + data);
                session.setAttribute(AuthConstant.LOGIN_USER,data);
                //返回登录页
                return "redirect:http://censmall.com";
            }else{
                return "redirect:http://auth.censmall.com/login.html";
            }
        }else{
            return "redirect:http://auth.censmall.com/login.html";
        }
    }

}
